package concurrent;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Created by chenxin34 on 2018/10/22 下午5:37.
 */
public class MapModifyTest {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "a");
        map.put(2, "b");
        map.put(3, "c");
        map.put(4, "d");
//        for (Iterator<Integer> keys = map.keySet().iterator(); keys.hasNext();) {
//            Integer key = keys.next();
//            String val = map.get(key);
//            map.remove(key);
//        }

//        for (Integer k : map.keySet()) {
//            map.remove(k);
//        }

        testCopyRemove();

        //ConcurrentModificationException
        Iterator<Map.Entry<Integer, String>> mapIt = map.entrySet().iterator();

        while (mapIt.hasNext()) {
            Map.Entry<Integer, String> entry = mapIt.next();
            if (entry.getValue().equals("c")) {
                map.remove(entry.getKey());
            }

        }
        System.out.println(map);


    }

    private static void testCopyRemove() {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "a");
        List<Integer> keySet = new ArrayList<>(map.keySet());
        Integer k = new Integer(1);
        keySet.remove(k);
        System.out.println(keySet);
        System.out.println(map);
    }
}
